var userInfo = {}
var teamInfo = {}
var contestInfo = {}
var identificationIcon = " <i class='am-icon-check' style='color: green'></i>"

var schoolID = {}
var IDSchool = {}


new Promise((resolve, reject) => {
    console.log("init contest..")
    getContestInfo(data => {
        $("#contestLoader").css('display', 'none')
        $("#contestContainer").css('display', 'block')
        contestInfo = data
        $("#contestName").text(data.name)
        $("#contestStartTime").text(data.start_time)
        $("#contestEndTime").text(data.end_time)
        $("#contestNote").html(data.note)
        tshirtSize = data.tshirt_size
        resolve()
    }, e => console.log(e))
}).then(() => new Promise((resolve, reject) => {
    resolve()
    // requestServer("/api/getSchoolID", "GET", defaultHeader.copy(), {}, data => {
    //     schoolID = data
    //     resolve()
    // }, () => {})
})).then(() => new Promise((resolve, reject) => {
    requestServer("/api/getIDSchool", "GET", defaultHeader.copy(), {}, data => {
        IDSchool = data
        for (let key in IDSchool) schoolID[IDSchool[key]] = key
        resolve()
    }, () => {})
})).then(() => new Promise((resolve, reject) => {
    // init user
    console.log("init user..")
    getUserInfo(data => {
        userInfo = data
        $("#userName").text(userInfo.name)
        $("#userSchool").html(IDSchool[userInfo.school] + (data.is_uestc_stu ? identificationIcon : ""))
        $("#userStuId").text(userInfo.stuid == "" ? "外校" : userInfo.stuid)

        $("#tshirt").text(userInfo.tshirt)

        $("#mname")[0].value = userInfo.name
        for(let school in schoolID) 
            $("#mschool").append("<option value='" + schoolID[school] + "' " + (school == userInfo.school ? "selected" : "") + ">" + school + "</option>")
        
        // construct tshirt
        for(let i=0;i<tshirtSize.length;i++) {
            if(tshirtSize[i] != data.tshirt) $("#size").append('<option value="' + tshirtSize[i] + '">' + tshirtSize[i] + '</option>')
            else $("#size").append('<option value="' + tshirtSize[i] + '" selected>' + tshirtSize[i] + '</option>')
        }

        $("#userLoader").css('display', 'none')
        $("#userContent").css('display', 'block')

        resolve()
    }, e => {
        $("#userLoader").css('display', 'none')
        $("#userNotLogin").css('display', 'block')
        $("#userNotLoginIcon").css('display', 'block')
        console.log(e)
        reject()
    })
})).then(() => new Promise((resolve, reject) => {
    // init team
    console.log("init team..")
    if(userInfo.teamid == 0) {
        $("#noTeam").css("display", "block")
        resolve()
        return;
    } 
    var suc = data => {
        teamInfo = data
        console.log(teamInfo)

        $("#teamName").text("队伍信息 - " + data.team_name + "(" + data.affiliation + ")")
        $("#teamID").text(data.team_id)
        $("#teamIC").text(data.invite_token)
        $("#teamAccount").text(data.account)
        $("#teamPwd").text(data.password)
        $("#teamMemCnt").text(data.mem_cnt)

        for(mi in data.member) {
            let member = data.member[mi]
            if(member.teamid != userInfo.teamid) continue
            $("#teamList").append("<tr><td class='am-text-center'>" + member.name + "</td><td class='am-text-center'>" + IDSchool[member.school] + (member.is_uestc_stu ? identificationIcon : "") + "</td><td class='am-text-center'>" + (member.stuid == "" ? "外校" : member.stuid) + "</td></tr>")
        }
        $("#teamContent").css("display", "block")
        resolve()
    }
    
    getTeamInfo(suc, e => {
        alert(e.msg)
        console.log(e)
        reject()
    })
}))

function loginSuc(data) {
    console.log(data)
    localStorage.setItem('token', data)
    alert("登录成功")
    window.location.reload()
}

function loginErr(err) {
    alert(err.msg)
    console.log(err)
}

function login(email, password) {
    var data = {email: email}
    if (email.length == 0) {
        alert('请输入邮箱');
        return;
    }
    if (password.length == 0) {
        alert('请输入密码');
        return;
    }
    if (password.length < 8) {
        alert('密码长度应不小于8位');
        return;
    }
    var hashSecret = CryptoJS.HmacSHA256(password, keySecret);
    data.pwd_token = CryptoJS.enc.Hex.stringify(hashSecret);
    
    postLogin(JSON.stringify(data), loginSuc, loginErr)
}

$("#mcancel").click(e => {
    $("#mContent").css("display", "none")
    $("#userContent").css("display", "block")
})

$("#mBtn").click(e => {
    $("#userContent").css("display", "none")
    $("#mContent").css("display", "block")
})

$("#mconfirm").click(e => {
    var data = {
        name: $("#mname")[0].value,
        school: parseInt($("#mschool")[0].value),
        tshirt: $("#size")[0].value
    }
    postModify(data, e => {
        alert("修改成功")
        window.location.reload()
    }, e => {
        alert("修改失败\n" + e.msg)
    })
})